package com.googlecode.lightest.core

import groovy.xml.MarkupBuilder
import org.codehaus.groovy.runtime.StackTraceUtils 
import org.codehaus.groovy.runtime.StringBufferWriter

public class LightestUtils {

    /**
     * Return the String representation of a stack trace with extraneous Groovy
     * MOP entries removed.
     * 
     * @param t
     */
    static String getSanitizedStackTrace(Throwable t) {
        def sb = new StringBuffer()
        def writer = new StringBufferWriter(sb)
        
        StackTraceUtils.sanitize(t)
        t.printStackTrace(new PrintWriter(writer))
        
        return sb.toString()
    }
    
    /**
     * Creates a Lightest suite file for a given set of test classes in a
     * temporary location, and returns the file.
     * 
     * @param testClasses  the LightestTestCase classes
     */
    static File createSuiteFile(List<Class> testClasses) {
        def suiteFile = File.createTempFile('lightest-suite', '.xml')
        def writer = new FileWriter(suiteFile)
        
        writeSuiteXML(testClasses, writer)

        return suiteFile
    }
    
    /**
     * Writes an XML representation of a Lightest suite file for a given
     * set of test classes, using the specified writer.
     * 
     * @param testClasses  the LightestTestCase classes
     */
    static void writeSuiteXML(List<Class> testClasses, Writer writer) {
        def builder = new MarkupBuilder(writer)
        
        builder.suite (name: 'Suite1', verbose: '1') {
            test (name: 'Test1') {
                classes {
                    for (testClass in testClasses) {
                        'class' (name: testClass.name)
                    }
                }
            }
        }
    }
}